package com.xiaok.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * 创建bean的工厂类
 * @Classname BeanUtils
 * @Description TODO
 * @Date 2020/9/29 19:05
 * @Created by xiaok
 */
@Component
public class BeanUtils  implements ApplicationContextAware {

    private  Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    private static ApplicationContext applicationContext;

    /**
     * 通过字节码获取 Bean 实例
     * @param clazz
     * @param <T>
     * @return
     */
    private static<T>  T getBean(Class<T> clazz){ return applicationContext.getBean(clazz);}

    /**
     * 通过名字 和 字节码获取 Bean 实例
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name,Class<T> clazz){
        return applicationContext.getBean(name,clazz);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(applicationContext != null ){
            applicationContext = applicationContext;
        }
        logger.info("ApplicationContext配置成功,可以通过ApplicationContext配置成功,getBean 获取对象. context: "+applicationContext);
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
